"""
服务注册表
管理所有可用服务的注册、发现和状态跟踪
"""

import asyncio
from enum import Enum
from typing import Dict, Any, Optional, List, Set, Callable
from datetime import datetime, timedelta
import json

class ServiceStatus(Enum):
    """服务状态枚举"""
    ACTIVE = "active"           # 活跃状态
    INACTIVE = "inactive"       # 非活跃状态
    MAINTENANCE = "maintenance" # 维护状态
    ERROR = "error"             # 错误状态

class ServiceRegistry:
    """简化版服务注册表，提供清晰的服务注册和发现API"""
    
    def __init__(self):
        self.services: Dict[str, Dict[str, Any]] = {}
        self.service_status: Dict[str, ServiceStatus] = {}
        self.service_health: Dict[str, bool] = {}
        self.service_metrics: Dict[str, Dict[str, Any]] = {}
        self.service_configs: Dict[str, Dict[str, Any]] = {}
        self.service_dependencies: Dict[str, Set[str]] = {}
        self._query_cache: Dict[str, Dict[str, float]] = {}
        self._cache_ttl = timedelta(minutes=5)
        self._last_cache_cleanup = datetime.now()
        self._lock = asyncio.Lock()
        # 添加备用服务映射
        self.fallback_services: Dict[str, List[str]] = {}
        self.similar_services: Dict[str, List[str]] = {}
        self.degraded_services: Dict[str, List[str]] = {}
        # 添加临时依赖映射
        self.temporary_dependency_mapping: Dict[str, str] = {}
    
    # ====================
    # 核心服务注册与发现接口
    # ====================
    
    def register_service(self, name: str, service_func: Callable, description: str = "", 
                        keywords: Optional[List[str]] = None, parameters: Optional[Dict[str, Any]] = None,
                        examples: Optional[List[str]] = None, version: str = "1.0.0"):
        """
        注册一个新服务
        
        Args:
            name: 服务名称
            service_func: 服务函数
            description: 服务描述
            keywords: 服务关键词列表
            parameters: 服务参数描述
            examples: 使用示例列表
            version: 服务版本
        """
        service_info = {
            "name": name,
            "function": service_func,
            "description": description,
            "keywords": keywords or [],
            "parameters": parameters or {},
            "examples": examples or [],
            "version": version,
            "registered_at": datetime.now().isoformat()
        }
        
        self.services[name] = service_info
        self.service_status[name] = ServiceStatus.ACTIVE
        self.service_health[name] = True
        self.service_metrics[name] = {
            "total_executions": 0,
            "successful_executions": 0,
            "failed_executions": 0,
            "total_execution_time": 0.0,
            "average_execution_time": 0.0
        }
        self.service_configs[name] = {}
        self._query_cache.clear()  # 清除缓存
    
    def get_service_info(self, name: str) -> Optional[Dict[str, Any]]:
        """
        获取服务信息
        
        Args:
            name: 服务名称
            
        Returns:
            服务信息字典，如果服务不存在则返回None
        """
        return self.services.get(name)
    
    def service_exists(self, name: str) -> bool:
        """
        检查服务是否存在
        
        Args:
            name: 服务名称
            
        Returns:
            服务是否存在
        """
        return name in self.services
    
    def get_all_services(self) -> Dict[str, Dict[str, Any]]:
        """
        获取所有服务信息
        
        Returns:
            所有服务信息的字典
        """
        return self.services.copy()
    
    def list_services(self) -> List[str]:
        """
        列出所有已注册的服务名称
        
        Returns:
            服务名称列表
        """
        return list(self.services.keys())
    
    def find_service_by_query(self, query: str) -> Optional[str]:
        """
        根据查询找到最匹配的服务
        
        Args:
            query: 用户查询文本
            
        Returns:
            最匹配的服务名称，如果没有匹配则返回None
        """
        relevant_services = self.find_relevant_services(query, top_n=1)
        if relevant_services:
            return relevant_services[0]['name']
        return None
    
    def find_relevant_services(self, query: str, top_n: int = 3) -> List[Dict[str, Any]]:
        """
        根据查询找到相关服务
        
        Args:
            query: 用户查询文本
            top_n: 返回最相关的服务数量
            
        Returns:
            相关服务信息列表
        """
        # 使用缓存提高性能
        cache_key = f"{query}_{top_n}"
        if cache_key in self._query_cache:
            # 从缓存获取结果
            cached_scores = self._query_cache[cache_key]
            sorted_services = sorted(cached_scores.items(), key=lambda x: x[1], reverse=True)[:top_n]
        else:
            # 计算匹配分数
            service_scores = {}
            for name, info in self.services.items():
                # 只考虑活跃状态的服务
                if self.service_status.get(name) not in [ServiceStatus.ACTIVE, ServiceStatus.MAINTENANCE]:
                    continue
                    
                # 计算查询与服务的匹配度
                score = self._calculate_match_score(query, info)
                service_scores[name] = score
            
            # 缓存结果
            self._query_cache[cache_key] = service_scores
            sorted_services = sorted(service_scores.items(), key=lambda x: x[1], reverse=True)[:top_n]
        
        # 构建结果列表
        results = []
        for name, score in sorted_services:
            service_info = self.services[name].copy()
            service_info['match_score'] = score
            results.append(service_info)
            
        return results
    
    def _calculate_match_score(self, query: str, service_info: Dict[str, Any]) -> float:
        """
        计算查询与服务的匹配分数
        
        Args:
            query: 查询文本
            service_info: 服务信息
            
        Returns:
            匹配分数 (0-1)
        """
        score = 0.0
        query_lower = query.lower()
        
        # 检查服务名称匹配
        if query_lower in service_info['name'].lower():
            score += 0.4
            
        # 检查描述匹配
        if query_lower in service_info['description'].lower():
            score += 0.3
            
        # 检查关键词匹配
        for keyword in service_info['keywords']:
            if query_lower in keyword.lower():
                score += 0.2
                break
                
        # 检查示例匹配
        for example in service_info['examples']:
            if query_lower in example.lower():
                score += 0.1
                break
                
        return min(score, 1.0)  # 确保不超过1.0
    
    # ====================
    # 服务状态管理接口
    # ====================
    
    def set_service_status(self, name: str, status: ServiceStatus):
        """
        设置服务状态
        
        Args:
            name: 服务名称
            status: 服务状态
        """
        if name in self.services:
            self.service_status[name] = status
    
    def get_service_status(self, name: str) -> ServiceStatus:
        """
        获取服务状态
        
        Args:
            name: 服务名称
            
        Returns:
            服务状态
        """
        return self.service_status.get(name, ServiceStatus.INACTIVE)
    
    def set_service_health(self, name: str, healthy: bool):
        """
        设置服务健康状态
        
        Args:
            name: 服务名称
            healthy: 是否健康
        """
        self.service_health[name] = healthy
    
    def is_service_healthy(self, name: str) -> bool:
        """
        检查服务是否健康
        
        Args:
            name: 服务名称
            
        Returns:
            是否健康
        """
        return self.service_health.get(name, False)
    
    # ====================
    # 服务依赖管理接口
    # ====================
    
    def add_service_dependency(self, service_name: str, dependency_name: str):
        """
        添加服务依赖
        
        Args:
            service_name: 服务名称
            dependency_name: 依赖服务名称
        """
        if service_name not in self.service_dependencies:
            self.service_dependencies[service_name] = set()
        self.service_dependencies[service_name].add(dependency_name)
    
    def get_service_dependencies(self, service_name: str) -> Set[str]:
        """
        获取服务依赖
        
        Args:
            service_name: 服务名称
            
        Returns:
            依赖服务名称集合
        """
        # 检查是否有临时依赖映射
        resolved_dependencies = set()
        for dep in self.service_dependencies.get(service_name, set()):
            # 如果有临时映射，使用映射后的服务
            resolved_dependencies.add(self.temporary_dependency_mapping.get(dep, dep))
        return resolved_dependencies
    
    # ====================
    # 服务指标管理接口
    # ====================
    
    def record_service_execution(self, name: str, execution_time: float, success: bool):
        """
        记录服务执行指标
        
        Args:
            name: 服务名称
            execution_time: 执行时间
            success: 是否成功
        """
        if name in self.service_metrics:
            metrics = self.service_metrics[name]
            metrics["total_executions"] += 1
            metrics["total_execution_time"] += execution_time
            metrics["average_execution_time"] = metrics["total_execution_time"] / metrics["total_executions"]
            
            if success:
                metrics["successful_executions"] += 1
            else:
                metrics["failed_executions"] += 1
    
    def get_service_metrics(self, name: str) -> Dict[str, Any]:
        """
        获取服务指标
        
        Args:
            name: 服务名称
            
        Returns:
            服务指标字典
        """
        return self.service_metrics.get(name, {})
    
    # ====================
    # 服务配置管理接口
    # ====================
    
    def set_service_config(self, name: str, config: Dict[str, Any]):
        """
        设置服务配置
        
        Args:
            name: 服务名称
            config: 配置字典
        """
        self.service_configs[name] = config
    
    def get_service_config(self, name: str) -> Dict[str, Any]:
        """
        获取服务配置
        
        Args:
            name: 服务名称
            
        Returns:
            配置字典
        """
        return self.service_configs.get(name, {})
    
    def get_all_health_status(self) -> Dict[str, bool]:
        """
        获取所有服务的健康状态
        
        Returns:
            服务健康状态字典
        """
        return self.service_health.copy()
    
    def get_all_metrics(self) -> Dict[str, Dict[str, Any]]:
        """
        获取所有服务的指标
        
        Returns:
            服务指标字典
        """
        return self.service_metrics.copy()
    
    def get_service_instances(self, service_name: str) -> List[Dict[str, Any]]:
        """
        获取服务实例信息
        
        Args:
            service_name: 服务名称
            
        Returns:
            服务实例列表
        """
        # 检查服务是否存在
        if not self.service_exists(service_name):
            return []
        
        # 获取服务状态和指标
        service_status = self.get_service_status(service_name)
        is_healthy = self.is_service_healthy(service_name)
        metrics = self.get_service_metrics(service_name)
        
        # 创建一个模拟的服务实例
        # 在实际系统中，这里应该返回真实的服务实例列表
        instance = {
            "instance_id": f"{service_name}_instance_001",
            "healthy": is_healthy,
            "status": service_status.value,
            "connections": metrics.get("active_connections", 0),
            "response_time": metrics.get("average_execution_time", 0.5),
            "error_rate": metrics.get("failed_executions", 0) / max(1, metrics.get("total_executions", 1)),
            "weight": 1,
            "last_heartbeat": datetime.now().isoformat()
        }
        
        return [instance]
    
    # ====================
    # 故障转移服务管理接口
    # ====================
    
    def register_fallback_services(self, service_name: str, fallback_list: List[str]):
        """
        注册服务的备用服务列表
        
        Args:
            service_name: 服务名称
            fallback_list: 备用服务名称列表
        """
        self.fallback_services[service_name] = fallback_list
    
    def find_fallback_services(self, service_name: str) -> List[str]:
        """
        查找服务的备用服务
        
        Args:
            service_name: 服务名称
            
        Returns:
            备用服务名称列表
        """
        return self.fallback_services.get(service_name, [])
    
    def register_similar_services(self, service_name: str, similar_list: List[str]):
        """
        注册服务的相似服务列表
        
        Args:
            service_name: 服务名称
            similar_list: 相似服务名称列表
        """
        self.similar_services[service_name] = similar_list
    
    def find_similar_services(self, service_name: str) -> List[str]:
        """
        查找服务的相似服务
        
        Args:
            service_name: 服务名称
            
        Returns:
            相似服务名称列表
        """
        return self.similar_services.get(service_name, [])
    
    def register_degraded_services(self, service_name: str, degraded_list: List[str]):
        """
        注册服务的降级服务列表
        
        Args:
            service_name: 服务名称
            degraded_list: 降级服务名称列表
        """
        self.degraded_services[service_name] = degraded_list
    
    def find_degraded_services(self, service_name: str) -> List[str]:
        """
        查找服务的降级服务
        
        Args:
            service_name: 服务名称
            
        Returns:
            降级服务名称列表
        """
        return self.degraded_services.get(service_name, [])
    
    def register_temporary_dependency_mapping(self, original_service: str, replacement_service: str):
        """
        注册临时依赖映射关系
        
        Args:
            original_service: 原始服务名称
            replacement_service: 替换服务名称
        """
        self.temporary_dependency_mapping[original_service] = replacement_service
    
    # ====================
    # 学习能力增强服务注册
    # ====================
    
    def register_learning_services(self):
        """注册学习能力增强相关服务"""
        # 注册增强的强化学习服务
        from src.services.enhanced_reinforcement_learning_service import get_enhanced_reinforcement_learning_service
        self.register_service(
            name="enhanced_reinforcement_learning",
            service_func=get_enhanced_reinforcement_learning_service,
            description="增强的强化学习服务，支持多维度奖励和自适应优化",
            keywords=["强化学习", "RL", "自适应", "优化"],
            version="1.0.0"
        )
        
        # 注册增量学习服务
        from src.services.incremental_learning_service import get_incremental_learning_service
        self.register_service(
            name="incremental_learning",
            service_func=get_incremental_learning_service,
            description="增量学习服务，支持模型持续更新和优化",
            keywords=["增量学习", "在线学习", "持续学习"],
            version="1.0.0"
        )
        
        # 注册在线学习服务
        from src.services.incremental_learning_service import get_online_learning_service
        self.register_service(
            name="online_learning",
            service_func=get_online_learning_service,
            description="在线学习服务，支持实时反馈学习",
            keywords=["在线学习", "实时学习", "反馈学习"],
            version="1.0.0"
        )
        
        # 注册知识演化服务
        from src.services.incremental_learning_service import get_knowledge_evolution_service
        self.register_service(
            name="knowledge_evolution",
            service_func=get_knowledge_evolution_service,
            description="知识演化服务，实现知识库内容的自动更新和演化",
            keywords=["知识演化", "知识更新", "知识管理"],
            version="1.0.0"
        )
        
        # 注册学习能力增强综合服务
        from src.services.learning_enhancement_service import get_learning_enhancement_service
        self.register_service(
            name="learning_enhancement",
            service_func=get_learning_enhancement_service,
            description="学习能力增强综合服务，整合多种学习机制",
            keywords=["学习增强", "综合学习", "智能学习"],
            version="1.0.0"
        )
        
        # 注册A/B测试集成服务
        from src.services.learning_enhancement_service import get_ab_testing_integration_service
        self.register_service(
            name="ab_testing",
            service_func=get_ab_testing_integration_service,
            description="A/B测试集成服务，支持多变量测试和在线测试",
            keywords=["A/B测试", "多变量测试", "在线测试"],
            version="1.0.0"
        )


# 全局服务注册表实例
service_registry = ServiceRegistry()
